package controller

import (
	"fmt"
	"gin-shop-admin/middleware"
	"gin-shop-admin/repository"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func GetMenus(c *gin.Context) {
	res, ok := c.Get("claims")
	claims, ok2 := res.(*middleware.CustomClaims)
	if !ok || !ok2{
		c.JSON(201, gin.H{"msg": "获取菜单列表失败", "data": nil})
		return
	}
	user_menus, api_path_map, err := repository.GetUserMenus(claims.ID)

	if len(user_menus) == 0 || err != nil{
		c.JSON(202, gin.H{"msg": "获取菜单列表失败", "menus": nil, "api_path_map": nil})
	}else {
		c.JSON(http.StatusOK, gin.H{"msg": "获取菜单列表成功", "menus": user_menus, "api_path_map": api_path_map})
	}
	return
}

func GetPermissionList(c *gin.Context)  {
	query, _ := c.GetQuery("query")
	page, pageOK := c.GetQuery("pageNum")
	limit, limitOK := c.GetQuery("pageSize")
	if !pageOK || !limitOK{
		c.JSON(201, gin.H{"msg": "参数获取失败", "data": nil, "total": 0})
		return
	}
	pageNum, _ := strconv.Atoi(page)
	pageSize, _ := strconv.Atoi(limit)
	total, permissionList,err := repository.GetPermissionList(query, pageNum, pageSize)
	if err != nil{
		fmt.Println(err)
		c.JSON(202, gin.H{"msg": "权限列表获取失败", "data": nil, "total": 0})
	}else {
		c.JSON(http.StatusOK, gin.H{"msg": "权限列表获取成功", "data": permissionList, "total": total})
	}
	return
}

func GetPermissionTree(c *gin.Context)  {
	permissionTreeList := repository.GetAllPermissionsTree()
	c.JSON(http.StatusOK, gin.H{"msg": "获取权限树成功", "data": permissionTreeList})
	return
}

func GetRoles(c *gin.Context)  {
	role_list, err := repository.GetRolesList()
	if err!=nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
	}else {
		c.JSON(http.StatusOK, gin.H{"msg": "获取角色列表成功", "data": role_list})
	}
	return
}

func DeleteRolePermission(c *gin.Context) {
	roleID, roleOK := c.Params.Get("roleID")
	permissionID, perOK := c.Params.Get("permissionID")
	if !roleOK || !perOK {
		c.JSON(201, gin.H{"msg": "参数获取失败", "data": nil})
		return
	}
	role_id, _ := strconv.Atoi(roleID)
	role, err := repository.DeleteRolePermission(role_id, permissionID)
	if err != nil {
		c.JSON(202, gin.H{"msg": err, "data": nil})
	} else {
		rolePermissions := repository.GetRolePermissions(role)
		c.JSON(http.StatusOK, gin.H{"msg": "删除成功", "data": rolePermissions})
	}
	return
}

func UpdateRolePermissions(c *gin.Context) {
	pids, pidOK := c.GetPostForm("pids")
	roleID, roleOK := c.Params.Get("roleID")
	if !pidOK || !roleOK {
		c.JSON(201, gin.H{"msg": "参数获取失败"})
		return
	}
	role_id, err := strconv.Atoi(roleID)
	if err != nil {
		c.JSON(202, gin.H{"msg": err})
		return
	}
	err = repository.UpdateRolePermission(role_id, pids)
	if err != nil {
		c.JSON(203, gin.H{"msg": err})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "分配权限成功"})
	}
	return
}